//microcommand define mcping
function textComponentToString(o) {
  if (typeof o === "string") return o.replace(/§./g, "")
  let str = o.text
  if (typeof o.translate === "string") str ??= o.fallback ?? o.translate
  str = String(str ?? "")
  if (o.extra) str += o.extra.map(textComponentToString).join("")
  return str
}
signature("<address>", { checkUnknown: true })
option("bedrock", "-b")
before(({ session, options, args }) => {
  if (options.help) return
  if (args.length > 1) return session.i18n("internal.redunant-arguments")
  if (args.length < 1) return session.i18n("internal.insufficient-arguments")
})
action(async ({ session, options: { bedrock } }, address) => {
  let hostname, port
  try {
    // According to the WHATWG URL spec, hostnames are punycode-encoded ("domain to ASCII") only for special schemes: <https://url.spec.whatwg.org/#hostname-state>, <https://url.spec.whatwg.org/#concept-host-parser>
    // Using special scheme http: to enable punycode encoding the hostname
    ;({ hostname, port } = new URL("http://" + address))
  } catch {
    return session.i18n(".invalid-url")
  }
  port = Number(port || (bedrock ? 19132 : 25565))
  const mineping = await import("@minescope/mineping")
  const output = []
  let result
  try {
    if (bedrock) {
      result = await mineping.pingBedrock(hostname, { port })
      output.push(session.i18n(".description", [textComponentToString(result.name)]))
      output.push(session.i18n(".version", [result.version.minecraftVersion]))
      output.push(session.i18n(".players", result.players))
      output.push(session.i18n(".game-mode", [result.gameMode]))
    } else {
      result = await mineping.pingJava(hostname, { port })
      if (typeof result.favicon === "string" && result.favicon.startsWith("data:image/png;base64,")) 
        output.push(h.image(result.favicon))
      if (result.description)
        output.push(session.i18n(".description", [textComponentToString(result.description)]))
      if (result.version?.name)
        output.push(session.i18n(".version", [textComponentToString(result.version.name)]))
      const sample = result.players?.sample?.filter(p => p.name !== "Anonymous Player")
      if (sample?.length)
        output.push(
          session.i18n(".players-with-sample", {
            ...result.players,
            sample: sample.map(p => p.name).join(session.text("general.comma")),
          })
        )
      else
        output.push(session.i18n(".players", result.players))
    }
    return output.map(line => h("p", line))
  } catch (err) {
    if (err?.message === "Socket timeout") return session.i18n(".timeout")
    if (err?.syscall) {
      ctx.logger.debug(err)
      return session.i18n(".connect-error")
    }
    ctx.logger.debug(err)
    return session.i18n(".parse-error")
  }
})
locale("zh-CN", {
  description: "查看 Minecraft 服务器信息",
  arguments: { address: "服务器地址" },
  options: { bedrock: "基岩版" },
  messages: {
    "invalid-url": "网址有误…",
    "connect-error": "连接失败…",
    timeout: "服务器响应超时…",
    "parse-error": "无法解析服务器信息…",
    version: "版本：{0}",
    description: "{0}<br/>",
    players: "在线玩家：{online} / {max}",
    "players-with-sample": "在线玩家：{online} / {max}（{sample}）",
    "game-mode": "游戏模式：{0}",
  },
})